package com.zhoug.common3.eventbus;


import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;


/**
 * @Author HK-LJJ
 * @Date 2020/3/10
 * @Description
 */
public class EventBusUtils {

    /**
     * 获取EvenBus
     * @return
     */
    public static EventBus getEventBus() {
        return EventBus.getDefault();
    }

    /**
     * 注册事件监听
     *
     * @param subscriber
     */
    public static void register(Object subscriber) {
        getEventBus().register(subscriber);
    }

    /**
     * 取消事件注册
     *
     * @param subscriber
     */
    public static void unregister(Object subscriber) {
        getEventBus().unregister(subscriber);
    }

    /**
     * 注册事件监听并且监听生命周期,销毁时自动取消注册
     * @param subscriber
     */
    public static void registerWithLifecycle(@NonNull LifecycleOwner subscriber){
        register(subscriber);
        subscriber.getLifecycle().addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                unregister(owner);
            }
        });
    }

    /**
     * 注册事件监听并且监听生命周期,销毁时自动取消注册
     * @param lifecycle
     */
    public static void registerWithLifecycle(@NonNull Lifecycle lifecycle){
        register(lifecycle);
        lifecycle.addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                unregister(owner);
            }
        });
    }


    /**
     * 发送事件
     * @param event
     */
    public static void post(@NonNull EventMessage event) {
        getEventBus().post(event);
    }

    /**
     * 发送事件
     * @param type
     */
    public static void post(int type){
        getEventBus().post(new EventMessage(type));
    }

    /**
     * 发送事件
     * @param type
     * @param message
     * @param data
     */
    public static void post(int type, String message, Serializable data){
        getEventBus().post(new EventMessage(type,message,data));
    }


    /**
     * 发送粘性事件:可以被以后才注册监听该事件的接受者接收到
     * @param event
     */
    public static void postSticky(@NonNull EventMessage event) {
        getEventBus().postSticky(event);
    }




}
